/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.metadata.schemasutilities;

import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;

import uk.ljmu.metadata.utilities.MetadataUtilities;

public class FoafUtilities {
	private static final Logger log = Logger.getLogger(FoafUtilities.class);
	//MANAGEMENT OF RDF-XML RECORDS FROM THE SCHEMA ELEMENTS
	//FOAF
	/**
	 * 
	 * @param prefixList
	 * 
	 * @return Document
	 */
	public static Document createEmptyFoafRecord(List<String> prefixList, String aboutID)
	{
		/*
		 * <rdf:RDF
      		xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
      		xmlns:foaf="http://xmlns.com/foaf/0.1/">
			<foaf:Person>
      			<foaf:name>Edd Dumbill</foaf:name>
      			<foaf:mbox rdf:resource="mailto:edd@xml.com" />
		  	</foaf:Person>
		  </rdf:RDF>
		 * */
		Element root = DocumentHelper.createElement( "rdf:RDF" );
		root.addNamespace("rdf", MetadataUtilities.RELS_MAP.get("rdf"));
		root.addNamespace("rdfs", MetadataUtilities.RELS_MAP.get("rdfs"));
		root.addNamespace("foaf", MetadataUtilities.MDSchemasUrl.get("foaf"));

		if (prefixList != null && prefixList.size() > 0)
		{
			for (String pref : prefixList)
			{
				String ns = MetadataUtilities.MDSchemasUrl.get(pref);
				if (ns == null)
					continue;
				root.addNamespace(pref, ns);
			}
		}
		/*
		 * <rdf:RDF
      		xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
      		xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
      		xmlns:foaf="http://xmlns.com/foaf/0.1/">
				<foaf:PersonalProfileDocument rdf:about="">
  					<foaf:maker rdf:resource="#me"/>
				</foaf:PersonalProfileDocument>
				<foaf:Person rdf:ID="me">
				</foaf:Person>
			</rdf:RDF>
		*/
		//Create document
		//Element personalProfile = root.addElement("foaf:PersonalProfileDocument");
		//personalProfile.addAttribute("rdf:about", aboutID);
		//Element foafMaker = personalProfile.addElement("foaf:maker");
		//foafMaker.addAttribute("rdf:resource", "#me");
		Element person = root.addElement( "foaf:Person" );
		//person.addAttribute("rdf:ID", "#me");
		person.addAttribute("rdf:about", aboutID);
		Document doc = DocumentHelper.createDocument(root);

		return doc;
	}
	/**
	 * Adds a Foaf Record to an existing RDF-XML document
	 * @param xmlContents existing RDF document where we want to add the foaf record
	 * @param ID of the foaf record
	 * @param prefixList list of the prefixes for the namespaces needed in the RDF document
	 * 
	 * @return Document
	 */
	public static Document createEmptyFoafRecordAllInOne(String xmlContents, String aboutID, List<String> prefixList)
	{
		
		if (xmlContents.equals("")) {
			Document doc = FoafUtilities.createEmptyFoafRecord(prefixList, aboutID);
			
			return doc;
		}
		else {
			//Create document
			Document doc = null;
				
			try 
			{
				doc = DocumentHelper.parseText(xmlContents);
			} catch (DocumentException e) {
				log.fatal(e.getMessage());
			}
			if (doc != null) {
				Element root = doc.getRootElement();
				
				if (prefixList != null && prefixList.size() > 0)
				{
					for (String pref : prefixList)
					{
						String ns = MetadataUtilities.MDSchemasUrl.get(pref);
						if (ns == null)
							continue;
						root.addNamespace(pref, ns);
					}
				}
				if (root.getNamespaceForPrefix("foaf") == null)
					root.addNamespace("foaf", MetadataUtilities.MDSchemasUrl.get("foaf"));
				Element person = root.addElement( "foaf:Person" );
				//person.addAttribute("rdf:ID", "#me");
				person.addAttribute("rdf:about", aboutID);
			}
	
			return doc;
		}
	}
	/**
	 * Add a property to an existing RDF description record
	 * 
	 * @param propertyName string with the property name
	 * @param propertyValue string with the value of the property
	 * @param xmlContents String containing the actual record in which to add the new property
	 * 
	 * @return Document with the properties added
	 */
	public static Document addFoafProperty(String propertyName, String propertyValue, String xmlContents)
	{
		//Create document
		Document doc = null;
		try 
		{
			doc = DocumentHelper.parseText(xmlContents);
		} catch (DocumentException e) {
			log.fatal(e.getMessage());
		}
		if (doc != null)
		{
			Element root = doc.getRootElement();
			Element desc = root.element("Person");
			Namespace ns = new Namespace("foaf", MetadataUtilities.MDSchemasUrl.get("foaf"));
			QName qname; 
			//Already Qualified
			if (!propertyName.contains(":"))
				qname = new QName(propertyName, ns);
			else qname = new QName(propertyName);
			
			Element property = DocumentHelper.createElement(qname);
			property.setText(propertyValue);
			desc.add(property);

			return doc;
		} 
		else
		{
			log.info("Error while creating XML Document");
			return null;
		}
	}
}
